import { Button, Modal, Toast } from "antd-mobile";
import React, { useEffect, useState } from "react";
import requewt from "@/utils/requewt";
import { API } from "@/config";
import callFeedback from "@/components/common/modalFeedback";
import { useRouter } from "next/router"
import { appNavigate, appTypeCheck, checkENV2, isValidArr, navigateTo, wxappNavigate } from "@/utils";
import * as gtag from "@/libs/gtag";
import { STATUS } from "@/components/pages/task/config";

export default function ({}) {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(undefined);
  const [env, setEnv] = useState(undefined);
  const [status, setStatus] = useState(undefined);
  const router = useRouter();
  const {aid} = router.query;

  useEffect(() => {
    (async () => {

      setEnv(await checkENV2());
      await handler.check(aid);
    })()

    return () => {
      Modal.clear();
      Toast.clear();
    }
  }, [])


  const handler = {
    // 获取活动状态
    check: async (aid) => {
      setLoading(true);
      await Toast.show({icon: 'loading', content: '加载中'})

      const resp = await requewt(API.activity.status, {body: {activity_id: aid}});
      Toast.clear();
      setLoading(false)
      console.log(`resp`, resp)
      if (resp?.error_code !== 0) {
        await Toast.clear();
        await callFeedback({title: resp?.msg || `请求失败`});
        return;
      }
      let _data = resp?.data;
      setData(_data);
      setStatus(_data?.status);
    },
    // 发帖
    post: async (url = data?.task_link) => {
      if (!url) return;
      const {type, value} = appTypeCheck(url) || {};
      console.log(type, value)

      if (env === `app`) {
        if (type && value) appNavigate(type, value);
        else await navigateTo(url);

        gtag.event({
          action: 'app_post_trigger',
          category: 'Post',
          label: `APP触发发帖`,
        })
      } else {
        await requewt(API.poster.create, {body: {activity_id: aid}});

        if (type && value) wxappNavigate(type, value);
        else await navigateTo(url);

        gtag.event({
          action: 'mini_post_trigger',
          category: 'Post',
          label: `小程序触发发帖`,
        })
      }
    },
    // 展示领取弹窗
    show: async () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal close-at-center-bottom`,
        title: <>恭喜您发帖成功</>,
        content: <div className="inner">
          <div className="thumb">
            <img className="prize-item" src={data?.code_icon || `/img/prize/prize-ticket.png`} alt="" />
            <img className="deco deco-stripe" src={`/img/prize/prize-stripe.png`} alt="" />
          </div>
          <div className="title">{data?.code_name || `未知`}</div>
          <div className="subtitle">兑换码 {data?.code_num}</div>
        </div>,
        actions: [
          <Button key={`cancel`} onClick={e => handler.receive()} size={`small`} shape={`rounded`}
                  className="act-btn act-btn-bevel">领取</Button>,
        ],
        closeOnAction: true,
        closeOnMaskClick: false,
      });
    },
    // 领取奖励
    receive: async () => {
      await Toast.show({icon: 'loading', content: '领取中'});
      const resp = await requewt(API.prize.receive, {body: {activity_id: aid}});

      console.log(`resp`, resp);
      await Toast.clear();
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        await callFeedback({title: resp?.msg || `领取失败`});
        return;
      }

      Modal.close()
    },
    jump: url => navigateTo(`${url}?aid=${aid}`),
  }

  return (
    <>
      <div className="position-center">

        <div className="content">
          <div className="title">
            - 完成发帖任务 -
            <br />
            领取美食代金券
          </div>

          <div className="prize">
            {
              STATUS[status]?.prize.showStripe ?
                <img className="deco deco-stripe" src="/img/prize/prize-stripe.png" alt="" />
                :
                null
            }

            <img className="prize-item" src={STATUS[status]?.prize.thumb} alt="" />

          </div>

        </div>
        <div className="footer">
          <Button shape={`rounded`} size={`small`}
                  loading={loading}
                  className="act-btn act-btn-bevel"
                  onClick={e => STATUS[status]?.btn?.action(handler)}
          >
            {STATUS[status]?.btn?.text}
          </Button>
        </div>
      </div>
    </>
  )
}